#!/bin/bash

# 获取项目根目录
PROJECT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# 确保日志目录存在
mkdir -p "${PROJECT_ROOT}/logs"

# 生成日志文件名（使用时间戳）
LOG_FILE="${PROJECT_ROOT}/logs/nohup_$(date +%Y%m%d_%H%M%S).log"

# 检查端口占用
PORT=8001
if lsof -i :$PORT > /dev/null; then
    echo "Port $PORT is in use. Killing existing process..."
    kill $(lsof -t -i:$PORT)
    sleep 1
fi

# 激活虚拟环境
source "${PROJECT_ROOT}/.venv/bin/activate"

# 使用 nohup 启动服务
nohup python -m uvicorn app.main:app \
    --host 0.0.0.0 \
    --port 8001 \
    --reload \
    > "${LOG_FILE}" 2>&1 &

# 输出进程信息
echo "Server started with PID: $!"
echo "Log file: ${LOG_FILE}"

# 等待服务启动
sleep 2

# 检查服务是否成功启动
if curl -s http://localhost:8001/docs > /dev/null; then
    echo "Server is running at http://localhost:8001"
else
    echo "Server failed to start. Check logs for details."
    tail -n 20 "${LOG_FILE}"
fi